import {
  baseUrl
} from './env'
import axios from 'axios'
import qs from 'qs'

let axiosIns = axios.create({})

// 默认配置
axiosIns.defaults.baseURL = baseUrl
axiosIns.defaults.responseType = 'json'
// axiosIns.defaults.xhrFields = {
//   withCredentials: true
// }
axiosIns.defaults.transformRequest = [function (data) {
  return qs.stringify(data)
}]
axiosIns.defaults.validateStatus = function (status) {
  return true
}

// 请求拦截器
axiosIns.interceptors.request.use(function (config) {
  // 配置config
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器即异常处理
axiosIns.interceptors.response.use(function (response) {
  let data = response.data
  let status = response.status
  if (status === 200) {
    return Promise.resolve(data)
  } else {
    return Promise.reject(response)
  }
})

let ajaxMethod = ['get', 'post']
let api = {}
ajaxMethod.forEach((method) => {
  // 数组取值的两种方式
  api[method] = function (uri, data, config) {
    return new Promise(function (resolve, reject) {
      // data.withCredentials = true
      axiosIns[method](uri, data, config).then((response) => {
        if (response.code === 200) {
          resolve(response)
        }
      }).catch((error) => {
        reject(error)
      })
    })
  }
})

export default api
